package pl.model.dao.impl;

import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.springframework.orm.hibernate3.HibernateJdbcException;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.transaction.annotation.Transactional;

import pl.model.dao.AuthorDao;
import pl.model.domain.Author;
import pl.model.domain.Book;


@Transactional
public class JpaAuthorDao extends JpaAbstractDao<Author> implements AuthorDao {

	@Override
	public Author find(final String name, final String surname) {
		Author author = (Author) getJpaTemplate().execute(new JpaCallback(){

			@Override
			public Object doInJpa(EntityManager em)
					throws PersistenceException {
				Query q = em.createQuery("from Author a where a.name = :name and a.surname = :surname").
					setParameter("name", name).setParameter("surname", surname);
				List l =q.getResultList();
				if (l.size() > 0) return l.get(0);
				else return null;
			}
			
		});
		return author;
	}

	@Override
	public Collection<Book> getAuthorBooks(Integer authorId) {
		Collection<Book> books = find(authorId).getBooks();
		log.info("dao got books");
		log.info("dao books size " + books.size());
    //	log.info("dao first book " + books.iterator().next());
		return books;
	}

	@Override
	@Transactional(noRollbackFor={HibernateJdbcException.class})
	public void persistIgnoreException(Author author) {
		log.info("persistIgnoreException start");
		try {
			log.info("before persist");
			getJpaTemplate().persist(author);
			flush();
		} catch (HibernateJdbcException e) {
			// TODO Auto-generated catch block
			log.info("blad " + e.getClass());
		}
		log.info("persistIgnoreException end");
	}

	protected static int counter;
	public void testNoRollback() {
		counter++;
		log.info("testNoRollback start");
		try {
			log.info("before persist");
			Author author = new Author("Jakub" + counter, "Sitek" + counter);
			getJpaTemplate().persist(author);
			
			author = new Author("Jakub" + counter, "Sitek" + counter);
			getJpaTemplate().persist(author);
			
			log.info("before flush");
			flush();
		} catch (HibernateJdbcException e) {
			log.info("blad " + e.getClass());
		}
		log.info("testNoRollback end");
		
	}
	
}
